import React, { useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import {
    Button,
    Form,
    Input,
    InputNumber,
    Switch,
    Upload,
    message
} from 'antd';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';

axios.defaults.baseURL = 'http://localhost:3000/';

const normFile = (e) => {
    if (Array.isArray(e)) {
        return e;
    }
    return e?.fileList;
};

const Space = () => {
    const navigator = useNavigate();
    const [formData, setFormData] = useState({
        title: '',
        image: [],
        sequence: null,
        status: false
    });

    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setFormData(prevData => ({
            ...prevData,
            [name]: value
        }));
    };

    const handleFileChange = (e) => {
        setFormData(prevData => ({
            ...prevData,
            image: normFile(e)
        }));
    };

    const handleSwitchChange = (checked) => {
        setFormData(prevData => ({
            ...prevData,
            status: checked
        }));
    };

    const handleSave = async () => {
        try {
            let imageUrl = '';
            if (formData.image && formData.image.length > 0) {
                const file = formData.image[0].originFileObj;
                const formDataToSend = new FormData();
                formDataToSend.append('file', file);
                const uploadResponse = await axios.post('/kai/uploads', formDataToSend);
                imageUrl = uploadResponse.data.path;
            }

            const dataToSend = {
                name:'李子凯',
                title: formData.title,
                status: formData.status ? 1 : 0,
                img: imageUrl
            };

            await axios.post('/kai/addslideShow', dataToSend, {
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            message.success('数据添加成功');
            navigator(-1);
        } catch (error) {
            message.error('数据添加失败');
            console.error('数据添加失败', error);
        }
    };

    return (
        <div
            style={{
                scrollbarWidth: 'none',
                overflowY: 'auto',
                margin: 'auto',
                width: '70%',
                height: '100%',
            }}
        >
            <div
                style={{
                    marginTop: '0.6rem',
                    overflow: 'hidden',
                    backgroundColor: 'white',
                    width: '100%',
                    height: '65%',
                    borderRadius: '20px',
                }}
            >
                <div style={{ display: 'flex', margin: '0.6rem' }}>
                    <div
                        style={{
                            width: '0.16rem',
                            marginTop: '0.1rem',
                            borderRadius: '0.1rem',
                            height: '0.6rem',
                            backgroundColor: '#3dd4a7',
                        }}
                    ></div>
                    <div style={{ fontSize: '0.5rem', marginLeft: '0.2rem' }}>新增轮播图</div>
                </div>
                <div>
                    <Form
                        labelCol={{
                            span: 4,
                        }}
                        wrapperCol={{
                            span: 14,
                        }}
                        layout="horizontal"
                        style={{
                            maxWidth: 600,
                        }}
                    >
                        <Form.Item label="标题">
                            <Input
                                name="title"
                                value={formData.title}
                                onChange={handleInputChange}
                            />
                        </Form.Item>
                        <Form.Item label="图片">
                            <Upload
                                listType="picture-card"
                                onChange={handleFileChange}
                                fileList={formData.image}
                            >
                                <button
                                    style={{
                                        border: 0,
                                        background: 'none',
                                    }}
                                    type="button"
                                >
                                    <PlusOutlined />
                                    <div
                                        style={{
                                            marginTop: 8,
                                        }}
                                    >
                                        Upload
                                    </div>
                                </button>
                            </Upload>
                        </Form.Item>
                        <Form.Item label="序号">
                            <InputNumber
                                name="sequence"
                                value={formData.sequence}
                                onChange={(value) => setFormData(prevData => ({
                                    ...prevData,
                                    sequence: value
                                }))}
                            />
                        </Form.Item>
                        <Form.Item label="状态">
                            <Switch
                                checked={formData.status}
                                onChange={handleSwitchChange}
                                checkedChildren="启用"
                                unCheckedChildren="禁用"
                            />
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 4, span: 14 }}>
                            <Button
                                style={{ background: '#5adbb5', width: '2rem', height: '1rem' }}
                                type="primary"
                                onClick={handleSave}
                            >
                                保存
                            </Button>
                            <Button
                                style={{ marginLeft: '1rem', width: '2rem', height: '1rem' }}
                                onClick={() => {
                                    navigator(-1);
                                }}
                                color="default"
                                variant="outlined"
                            >
                                返回
                            </Button>
                        </Form.Item>
                    </Form>
                </div>
            </div>
        </div>
    );
};

export default Space;